package cn.com.dashihui.web.controller;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;

import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.StoreTip;
import cn.com.dashihui.web.service.StoreTipService;

public class StoreTipController extends BaseController{
	private static final Logger logger = Logger.getLogger(StoreTipController.class);
	private StoreTipService service = Duang.duang(StoreTipService.class);

    public void index(){
        render("index.jsp");
    }

	public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPage(pageNum, pageSize, getStoreid()));
	}
	
	public void doSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		service.sortAd(sortMap);
    		renderSuccess();
    		return;
    	}
    	renderFailed();
    }

	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：内容为空，2：内容过长
	 */
	public void doAdd(){
		//内容
		String content = getPara("content");
		//是否显示
		int isShow = getParaToInt("isShow",1);
		if(StrKit.isBlank(content)){
			renderResult(1);
			return;
		}else if(content.length()>50){
			renderResult(2);
			return;
		}else{
			//保存
			if(service.addTip(new StoreTip()
				.set("content", content)
				.set("isShow", isShow)
				.set("storeid", getStoreid()))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}

	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：内容为空，2：内容过长
	 */
	public void doEdit(){
		//ID
		String tipid = getPara("tipid");
		//内容
		String content = getPara("content");
		//是否显示
		int isShow = getParaToInt("isShow",1);
		if(StrKit.isBlank(content)){
			renderResult(1);
			return;
		}else if(content.length()>50){
			renderResult(2);
			return;
		}else{
			//更新
			if(service.editTip(new StoreTip()
				.set("id", tipid)
				.set("content", content)
				.set("isShow", isShow))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&service.delTip(id)){
			logger.info("删除店铺通知【"+id+"】");
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
